package com.imooc.pay.controller;

import com.imooc.pay.pojo.PayInfo;
import com.imooc.pay.service.IPayService;
import com.lly835.bestpay.config.WxPayConfig;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/pay")
@Slf4j
public class PayController {

    @Autowired
    IPayService payService;


    @Autowired
    WxPayConfig wxPayConfig;

    //生成付款码
    @RequestMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("amount") BigDecimal amount,
                               @RequestParam("payType") BestPayTypeEnum bestPayTypeEnum) {
        PayResponse payResponse = payService.create(orderId, amount, bestPayTypeEnum);
        ModelAndView mv = new ModelAndView();

        Map map = new HashMap<>();
        //wxnative返回的是一个文本url，我们可以拿到直接生成二维码，支付宝pc 返回的是一个表单
        //所以支付方式不同，渲染方式就不同，wx native map.put("codeUrl",payResponse.getCodeUrl());
        //ALI_PC使用body
        if (bestPayTypeEnum == BestPayTypeEnum.WXPAY_NATIVE) {
            map.put("codeUrl", payResponse.getCodeUrl());
            map.put("orderId",orderId);
            map.put("returnUrl",wxPayConfig.getReturnUrl());
            mv.addAllObjects(map);
            mv.setViewName("createForWxNative");
        } else if (bestPayTypeEnum == BestPayTypeEnum.ALIPAY_PC) {
            map.put("body", payResponse.getBody());
            mv.addAllObjects(map);
            mv.setViewName("createForAlipayPC");
        }

        return mv;
    }

    //扫码支付之后，微信会调用这个接口
    // wxPayConfig.setNotifyUrl("http://jin.xiaomy.net/pay/notify")
    //aliPayConfig.setNotifyUrl("http://jin.xiaomy.net/pay/notify");
    @RequestMapping("/notify")
    @ResponseBody
    public String asnycNotify(@RequestBody String notifyData) {
        log.info("wx return notifyData==>>{}", notifyData);
        return payService.asyncNotify(notifyData);
    }

    @RequestMapping("/test")
    @ResponseBody
    public String test() {

        return payService.testSql();
    }


    @GetMapping("/queryStatus")
    @ResponseBody
    public PayInfo queryStatus(@RequestParam String orderId){
        log.info("查询支付记录==》》{}",orderId);
        return payService.queryStatus(orderId);


    }


}
